package com.example.tabbar.fragment

import android.os.Bundle

import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tabbar.R
import com.example.tabbar.adapter.PermissionAdapter
import com.example.tabbar.databinding.FragmentEditRoleBinding
import com.junray.usermangement.listener.OnUpdatePermissionListener
import com.junray.usermangement.room.entity.Permission
import com.junray.usermangement.room.entity.Role
import com.junray.usermangement.room.entity.RolePermission
import com.junray.usermangement.utils.LiveDataUtils.observeOnce
import com.junray.usermangement.utils.SessionManager
import com.junray.usermangement.viewModel.UserViewModel


class EditRoleFragment : Fragment() {
    private var binding: FragmentEditRoleBinding? = null
    private var permissionView: RecyclerView? = null
    private var permissionAdapter: PermissionAdapter? = null
    private var roleId: Long? = null // 添加角色ID字段
    private var viewmodel: UserViewModel? = null
    private var roleName: EditText? = null
    private var oldPermission: List<Permission>? = null
    private var sessionManager: SessionManager? = null
    private var currentUserRoleId: Long? = null
    private var editName: String? = null
    private var roleLevelGroup: RadioGroup? = null
    private var distributor: RadioButton? = null
    private var admin: RadioButton? = null
    private var manager: RadioButton? = null
    private var operator: RadioButton? = null
    // 编辑角色id
    private var editRoleLevel: Int? = 0
    private var currentRoleLevel: Int? = 4


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            val id = it.getLong(ARG_USER_ID, -1)
            val userName = it.getString(ARG_USER_NAME)
            val level = it.getInt(ARG_ROLE_LEVEL)
            if (id != -1L) {
                roleId = id
                editName = userName
                editRoleLevel = level
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentEditRoleBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()

        setView()

        onClick()
    }

    private fun onClick() {
        binding!!.editBack.setOnClickListener {
            // 返回上一页
            parentFragmentManager.popBackStack()
        }

        // 设置全选CheckBox的监听器
        binding!!.selectAll.setOnCheckedChangeListener { _, isChecked ->
            permissionAdapter?.selectAll(isChecked)
        }

        binding?.roleSave?.setOnClickListener {
            saveRole()
        }
    }

    private fun initView() {
        viewmodel= ViewModelProvider(this)[(UserViewModel::class.java)]
        roleName = binding!!.etRoleName
        sessionManager = SessionManager.instance
        currentUserRoleId = sessionManager?.roleId

        permissionView = binding!!.permissionList
        permissionAdapter = PermissionAdapter()
        permissionView?.adapter = permissionAdapter
        permissionView?.layoutManager = GridLayoutManager(requireContext(), 2)

        // 获取当前用户角色级别
        currentRoleLevel = sessionManager?.currentRoleLevel

        roleLevelGroup = binding!!.roleLevelGroup
        distributor = binding!!.distributor
        admin = binding!!.admin
        manager = binding!!.manager
        operator = binding!!.operator

        if (roleId == null) {
            // 新建角色
            operator?.isChecked = true
        }
        // 设置适配器的全选状态监听器
        permissionAdapter?.setSelectAllListener { isAllSelected ->
            // 避免重复触发监听器
            binding!!.selectAll.setOnCheckedChangeListener(null)
            binding!!.selectAll.isChecked = isAllSelected
            binding!!.selectAll.setOnCheckedChangeListener { _, isChecked ->
                permissionAdapter?.selectAll(isChecked)
            }
        }
    }

    private fun setView() {
        if (roleId == null) {
            // 新建用户
            setupForNewUser()
            filterRoleLevelsByCurrentUser()

        } else {
            // 编辑用户
            setupForEditUser()
            filterRoleLevelsByCurrentUser()
        }
    }

    private fun saveRole() {
        val currentUserRoleLevel = currentRoleLevel ?: 4

        val selectedLevel = when (roleLevelGroup?.checkedRadioButtonId) {
            R.id.distributor -> 1
            R.id.admin -> 2
            R.id.manager -> 3
            R.id.operator -> 4
            else -> 4
        }

        // 检查是否有权限创建该级别的角色
        if (!canCreateRoleLevel(currentUserRoleLevel, selectedLevel)) {
            Toast.makeText(requireContext(), "您没有权限创建此级别的角色", Toast.LENGTH_SHORT).show()
            return
        }

        // 保存用户信息
        val roleName = roleName?.text.toString().trim()
        val roles = permissionAdapter?.getSelectedPermissions()
        if (roleName.isEmpty()) {
            Toast.makeText(requireContext(), R.string.tb_role_name_not_null, Toast.LENGTH_SHORT).show()
            return
        }
        if (roles.isNullOrEmpty()) {
            Toast.makeText(requireContext(), R.string.tb_least_select_one_permission, Toast.LENGTH_SHORT).show()
            return
        }
        observeOnce(
            viewmodel!!.countByRolename(roleName), viewLifecycleOwner
        ) { count: Int? ->
            if (count != null && count > 0) {
                val isEditingSameRoleWithName = (roleId != null && roleName == editName && count == 1)

                if (!isEditingSameRoleWithName) {
                    Toast.makeText(
                        requireContext(),
                        com.junray.usermangement.R.string.um_error_role_exists,
                        Toast.LENGTH_SHORT
                    ).show()
                    return@observeOnce
                }
            }

            val role = Role(roleName, "")

            role.level = selectedLevel // 设置级别
            if (roleId == null) {
                viewmodel!!.createRole(
                    role
                ) { roleId: Long ->
                    // 为新角色分配权限
                    roles.forEach { permission ->
                        val rolePermission = RolePermission(roleId, permission.id)
                        viewmodel?.insertRolePermission(rolePermission)
                    }
                    parentFragmentManager.popBackStack()
                }
            } else {
                var isUpdate = false
                if (roleName != editName) {
                    editName = roleName
                    viewmodel?.updateRoleName(roleId!!, roleName)
                    isUpdate = true
                }
                // 编辑的角色等级不等于选中后的等级
                if (selectedLevel != editRoleLevel) {
                    viewmodel?.updateRoleLevel(roleId!!, selectedLevel)
                    editRoleLevel = selectedLevel
                    isUpdate = true
                }

                // 直接修改原先的比较，使用ID集合比较
                val currentPermissionIds = roles.map { it.id }
                val oldPermissionIds = oldPermission?.map { it.id } ?: emptyList()
                if (currentPermissionIds != oldPermissionIds) {
                    viewmodel?.updateRolePermission(
                        roleId!!,
                        currentPermissionIds,
                        oldPermissionIds,
                        object :
                            OnUpdatePermissionListener {
                            override fun updatePermission() {
                                if (roleId == currentUserRoleId) {
                                    viewmodel!!.getRolePermissionName(roleId!!).observe(
                                        viewLifecycleOwner
                                    ) { permissions: MutableList<Permission> ->
                                        if (permissions.isNotEmpty()) {
                                            sessionManager!!.updatePermission(permissions) // 更新当前用户的权限缓存
                                        } else {
                                            sessionManager!!.updatePermission(ArrayList())
                                        }
                                    }
                                }
                                if (!isUpdate) {
                                    Toast.makeText(requireContext(), R.string.tb_role_update_success, Toast.LENGTH_SHORT).show()
                                }
                                // 返回上一页面
                                parentFragmentManager.popBackStack()
                            }

                            override fun onError(e: Exception) {}
                        }
                    )
                } else if (isUpdate) {
                    // 如果只有名称或等级更新，则显示成功消息并返回
                    Toast.makeText(requireContext(), R.string.tb_role_update_success, Toast.LENGTH_SHORT).show()
                    parentFragmentManager.popBackStack()
                }
            }
        }
    }

    private fun setupForNewUser() {
        binding?.editTitle?.text = getString(R.string.tb_setting_add_role)

        // 加载可分配的权限列表
        loadAvailablePermissions(false)
    }

    private fun setupForEditUser() {
        binding?.editTitle?.text = getString(R.string.tb_setting_edit_role)
        roleName?.setText(editName)

        val level = editRoleLevel ?: 4
        when (level) {
            1 -> distributor?.isChecked = true
            2 -> admin?.isChecked = true
            3 -> manager?.isChecked = true
            4 -> operator?.isChecked = true
        }

        // 加载可分配的权限列表，并设置当前角色权限为选中状态
        loadAvailablePermissions(true)
    }

    private fun loadAvailablePermissions(isEditMode: Boolean = false) {
        val permissionObserver = { permissions: List<Permission>? ->
            val permissionList = permissions ?: emptyList()
            permissionAdapter?.setItems(permissionList)

            if (isEditMode && roleId != null) {
                // 在编辑模式下，设置当前角色的权限为选中状态
                viewmodel?.getRolePermissionName(roleId!!)?.observe(viewLifecycleOwner) { editRolePermissions: List<Permission>? ->
                    if (!editRolePermissions.isNullOrEmpty()) {
                        setSelectedPermissions(permissionList, editRolePermissions)
                        oldPermission = editRolePermissions
                    }
                }
            }
        }


        viewmodel?.allPermission?.observe(viewLifecycleOwner, permissionObserver)
    }

    private fun setSelectedPermissions(allPermissions: List<Permission>, selectedPermissions: List<Permission>) {
        // 创建一个Set来存储选中权限的ID，提高查找效率
        val selectedPermissionIds = selectedPermissions.map { it.id }.toSet()

        // 通过反射访问selectedPositions字段（需要在Adapter中添加public方法）
        val selectedPositions = mutableSetOf<Int>()

        // 遍历所有权限，找出需要选中的项
        allPermissions.forEachIndexed { index, permission ->
            if (selectedPermissionIds.contains(permission.id)) {
                selectedPositions.add(index)
            }
        }

        // 更新选中状态
        updateAdapterSelection(selectedPositions)
    }
    private fun updateAdapterSelection(selectedPositions: Set<Int>) {
        // 需要在PermissionAdapter中添加这个公共方法
        permissionAdapter?.updateSelectedPositions(selectedPositions)
    }

    // 添加根据当前用户级别过滤可选角色级别的方法
    private fun filterRoleLevelsByCurrentUser() {

        // 根据当前用户级别限制可创建/编辑的角色级别
        when (currentRoleLevel) {
            1 -> {
//                enableAllRoleLevels()
                disableRoleLevels(listOf(distributor))
                enableRoleLevels(listOf(admin,manager,operator))
            }
            2 -> {
                // 管理员只能创建级别3和4的角色
                disableRoleLevels(listOf(distributor,admin))
                enableRoleLevels(listOf(manager,operator))
            }
            3 -> {
                // 主管只能创建级别4的角色
                disableRoleLevels(listOf(distributor,admin,manager))
                enableRoleLevels(listOf(operator))
            }
            else -> {
                // 操作员无权限创建角色
                disableAllRoleLevels()
            }
        }
    }

    // 启用所有角色级别选项
    private fun enableAllRoleLevels() {
        listOf(distributor, admin, manager, operator).forEach { it?.isEnabled = true }
    }

    // 禁用所有角色级别选项
    private fun disableAllRoleLevels() {
        listOf(distributor, admin, manager, operator).forEach { it?.isEnabled = false }
    }

    // 启用指定的角色级别选项
    private fun enableRoleLevels(levels: List<RadioButton?>) {
        levels.forEach { it?.isEnabled = true }
    }

    // 禁用指定的角色级别选项
    private fun disableRoleLevels(levels: List<RadioButton?>) {
        levels.forEach { it?.isEnabled = false }
    }

    // 判断当前用户是否有权限创建指定级别的角色
    private fun canCreateRoleLevel(currentUserLevel: Int, targetLevel: Int): Boolean {
        return when (currentUserLevel) {
            1 -> true  // 经销商可以创建所有级别
            2 -> targetLevel >= 3 // 管理员只能创建主管和操作员
            3 -> targetLevel >= 4  // 主管只能创建操作员
            else -> false  // 操作员无权限创建角色
        }
    }

    companion object {
        private const val ARG_USER_ID = "user_id"
        private const val ARG_USER_NAME = "user_name"
        private const val ARG_ROLE_LEVEL = "role_level"

        @JvmStatic
        fun newInstance(roleId: Long? = null, userName: String? = "",roleLevel: Int = 4 ) =
            EditRoleFragment().apply {
                arguments = Bundle().apply {
                    if (roleId != null) {
                        putLong(ARG_USER_ID, roleId)
                        putString(ARG_USER_NAME, userName)
                        putInt(ARG_ROLE_LEVEL, roleLevel)
                    }
                }
            }
    }
}